package com.neuedu.yyzx.controller;

import com.neuedu.yyzx.po.FileInfo;
import com.neuedu.yyzx.service.FileInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
public class FileUploadController {


    @Autowired
    FileInfoService fileInfoService;
    private String UPLOAD_DIR = "D:\\upload";


    /**
     * http://localhost:8080/upload
     * pic: xxxxxx
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    FileInfo upload(MultipartFile file) throws IOException {
        // 1 将临时空间的文件，转储到 D:\\upload
        String originalFileName = file.getOriginalFilename();
        // 扩展名
        String ext = originalFileName.substring(originalFileName.lastIndexOf("."));
        // 转储的新文件名
        String newFileName = UUID.randomUUID().toString() + ext;
        // 转储到 D:\\upload 下的  uuid.png/uuid.jpg
        file.transferTo(new File(UPLOAD_DIR, newFileName));
        // 2 将数据存储到 db
        /**
         * 当前时间
         * 上传的ip
         * 操作的工号
         * 上传的文件名
         *
         */

        FileInfo fileInfo = new FileInfo();


        fileInfo.setOriginName(originalFileName);
        fileInfo.setExt(ext);
        fileInfo.setPath(newFileName);
        fileInfo.setCreateTime(new Date());
        fileInfo.setSize(file.getSize());
        boolean success = fileInfoService.save(fileInfo);

        // 3 跳转到列表页

        return fileInfo;
    }


    /**
     * http://localhost:8080/downlod/3
     *
     * @param fid
     * @return
     * @throws IOException
     */
    @GetMapping("/downlod/{fid}")
    public ResponseEntity download2(@PathVariable Long fid) throws IOException {


        // 根据文件ID 查询  完整登路径
        FileInfo info = fileInfoService.getById(fid);


        return ResponseEntity.ok().
                header(HttpHeaders.CONTENT_TYPE, "application/octet-stream").
                header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + info.getOriginName()).
                body(new FileSystemResource(new File(UPLOAD_DIR, info.getPath())));

    }


}